package com.laundry.user.ui.orders

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.*
import androidx.fragment.app.Fragment
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.laundry.user.data.model.Order
import com.laundry.user.data.model.OrderStatus
// import com.laundry.user.data.repository.OrderRepository
import kotlinx.coroutines.launch

class OrdersFragment : Fragment() {

    private lateinit var orderRepository: OrderRepository
    private lateinit var tabLayout: LinearLayout
    private lateinit var ordersRecyclerView: RecyclerView
    private lateinit var emptyView: LinearLayout
    private lateinit var ordersAdapter: OrdersAdapter
    
    private var currentStatus: Int? = null
    private val statusTabs = listOf(
        "全部" to null,
        "待接单" to OrderStatus.PENDING.value,
        "进行中" to OrderStatus.ACCEPTED.value,
        "已完成" to OrderStatus.DELIVERED.value
    )

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        orderRepository = OrderRepository(requireContext())
        return createView()
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        setupAdapter()
        setupTabs()
        loadOrders()
    }

    private fun createView(): View {
        val mainLayout = LinearLayout(requireContext()).apply {
            orientation = LinearLayout.VERTICAL
            layoutParams = ViewGroup.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.MATCH_PARENT
            )
        }

        // 标题栏
        val titleBar = createTitleBar()
        
        // 状态标签栏
        tabLayout = createTabLayout()
        
        // 订单列表
        ordersRecyclerView = RecyclerView(requireContext()).apply {
            layoutParams = LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.MATCH_PARENT,
                0,
                1f
            )
            layoutManager = LinearLayoutManager(requireContext())
        }

        // 空状态视图
        emptyView = createEmptyView()

        mainLayout.addView(titleBar)
        mainLayout.addView(tabLayout)
        mainLayout.addView(ordersRecyclerView)
        mainLayout.addView(emptyView)

        return mainLayout
    }

    private fun createTitleBar(): LinearLayout {
        val titleBar = LinearLayout(requireContext()).apply {
            orientation = LinearLayout.HORIZONTAL
            setPadding(16, 16, 16, 16)
            gravity = android.view.Gravity.CENTER_VERTICAL
            layoutParams = LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.WRAP_CONTENT
            )
            background = createTitleBackground()
        }

        val titleText = TextView(requireContext()).apply {
            text = "我的订单"
            textSize = 20f
            setTextColor(android.graphics.Color.WHITE)
            layoutParams = LinearLayout.LayoutParams(
                0,
                LinearLayout.LayoutParams.WRAP_CONTENT,
                1f
            )
        }

        titleBar.addView(titleText)
        return titleBar
    }

    private fun createTabLayout(): LinearLayout {
        val tabLayout = LinearLayout(requireContext()).apply {
            orientation = LinearLayout.HORIZONTAL
            setPadding(0, 0, 0, 0)
            layoutParams = LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.WRAP_CONTENT
            )
            background = createTabBackground()
        }

        return tabLayout
    }

    private fun createEmptyView(): LinearLayout {
        val emptyView = LinearLayout(requireContext()).apply {
            orientation = LinearLayout.VERTICAL
            gravity = android.view.Gravity.CENTER
            setPadding(40, 40, 40, 40)
            layoutParams = LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.MATCH_PARENT,
                0,
                1f
            )
            visibility = View.GONE
        }

        val emptyIcon = ImageView(requireContext()).apply {
            setImageResource(android.R.drawable.ic_menu_agenda)
            layoutParams = LinearLayout.LayoutParams(120, 120)
        }

        val emptyText = TextView(requireContext()).apply {
            text = "暂无订单"
            textSize = 16f
            setTextColor(android.graphics.Color.parseColor("#999999"))
            gravity = android.view.Gravity.CENTER
            setPadding(0, 16, 0, 0)
        }

        emptyView.addView(emptyIcon)
        emptyView.addView(emptyText)
        return emptyView
    }

    private fun setupAdapter() {
        ordersAdapter = OrdersAdapter { order ->
            // TODO: 跳转到订单详情页
            Toast.makeText(requireContext(), "点击了订单: ${order.orderNo}", Toast.LENGTH_SHORT).show()
        }
        ordersRecyclerView.adapter = ordersAdapter
    }

    private fun setupTabs() {
        statusTabs.forEachIndexed { index, (title, status) ->
            val tabButton = Button(requireContext()).apply {
                text = title
                textSize = 14f
                setPadding(20, 16, 20, 16)
                layoutParams = LinearLayout.LayoutParams(
                    0,
                    LinearLayout.LayoutParams.WRAP_CONTENT,
                    1f
                )
                background = if (index == 0) createSelectedTabBackground() else createTabButtonBackground()
                setTextColor(if (index == 0) android.graphics.Color.WHITE else android.graphics.Color.parseColor("#666666"))
                
                setOnClickListener {
                    selectTab(index, status)
                }
            }
            tabLayout.addView(tabButton)
        }
    }

    private fun selectTab(selectedIndex: Int, status: Int?) {
        currentStatus = status
        
        // 更新标签样式
        for (i in 0 until tabLayout.childCount) {
            val tabButton = tabLayout.getChildAt(i) as Button
            if (i == selectedIndex) {
                tabButton.background = createSelectedTabBackground()
                tabButton.setTextColor(android.graphics.Color.WHITE)
            } else {
                tabButton.background = createTabButtonBackground()
                tabButton.setTextColor(android.graphics.Color.parseColor("#666666"))
            }
        }
        
        // 重新加载订单
        loadOrders()
    }

    private fun loadOrders() {
        lifecycleScope.launch {
            try {
                val result = orderRepository.getOrders(status = currentStatus)
                
                if (result.isSuccess) {
                    val orders = result.getOrNull()?.items ?: emptyList()
                    if (orders.isEmpty()) {
                        showEmptyView()
                    } else {
                        showOrdersList(orders)
                    }
                } else {
                    showEmptyView()
                    Toast.makeText(
                        requireContext(),
                        "加载订单失败: ${result.exceptionOrNull()?.message}",
                        Toast.LENGTH_SHORT
                    ).show()
                }
            } catch (e: Exception) {
                showEmptyView()
                Toast.makeText(requireContext(), "加载订单失败", Toast.LENGTH_SHORT).show()
            }
        }
    }

    private fun showOrdersList(orders: List<Order>) {
        ordersRecyclerView.visibility = View.VISIBLE
        emptyView.visibility = View.GONE
        ordersAdapter.updateData(orders)
    }

    private fun showEmptyView() {
        ordersRecyclerView.visibility = View.GONE
        emptyView.visibility = View.VISIBLE
    }

    private fun createTitleBackground(): android.graphics.drawable.Drawable {
        val drawable = android.graphics.drawable.GradientDrawable()
        drawable.setColor(android.graphics.Color.parseColor("#2196F3"))
        return drawable
    }

    private fun createTabBackground(): android.graphics.drawable.Drawable {
        val drawable = android.graphics.drawable.GradientDrawable()
        drawable.setColor(android.graphics.Color.parseColor("#F5F5F5"))
        return drawable
    }

    private fun createSelectedTabBackground(): android.graphics.drawable.Drawable {
        val drawable = android.graphics.drawable.GradientDrawable()
        drawable.setColor(android.graphics.Color.parseColor("#2196F3"))
        drawable.cornerRadius = 4f
        return drawable
    }

    private fun createTabButtonBackground(): android.graphics.drawable.Drawable {
        val drawable = android.graphics.drawable.GradientDrawable()
        drawable.setColor(android.graphics.Color.TRANSPARENT)
        return drawable
    }
}

// 订单适配器
class OrdersAdapter(
    private val onItemClick: (Order) -> Unit
) : RecyclerView.Adapter<OrdersAdapter.ViewHolder>() {

    private var orders = listOf<Order>()

    fun updateData(newOrders: List<Order>) {
        orders = newOrders
        notifyDataSetChanged()
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        val itemView = LinearLayout(parent.context).apply {
            orientation = LinearLayout.VERTICAL
            setPadding(16, 16, 16, 16)
            layoutParams = ViewGroup.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.WRAP_CONTENT
            ).apply {
                if (this is ViewGroup.MarginLayoutParams) {
                    bottomMargin = 8
                }
            }
            background = createItemBackground()
        }

        // 订单头部
        val headerLayout = LinearLayout(parent.context).apply {
            orientation = LinearLayout.HORIZONTAL
            gravity = android.view.Gravity.CENTER_VERTICAL
        }

        val merchantNameView = TextView(parent.context).apply {
            textSize = 16f
            setTextColor(android.graphics.Color.parseColor("#333333"))
            layoutParams = LinearLayout.LayoutParams(
                0,
                LinearLayout.LayoutParams.WRAP_CONTENT,
                1f
            )
        }

        val statusView = TextView(parent.context).apply {
            textSize = 14f
            setTextColor(android.graphics.Color.parseColor("#2196F3"))
        }

        headerLayout.addView(merchantNameView)
        headerLayout.addView(statusView)

        // 订单信息
        val orderNoView = TextView(parent.context).apply {
            textSize = 14f
            setTextColor(android.graphics.Color.parseColor("#666666"))
            setPadding(0, 8, 0, 0)
        }

        val amountView = TextView(parent.context).apply {
            textSize = 16f
            setTextColor(android.graphics.Color.parseColor("#FF5722"))
            setPadding(0, 8, 0, 0)
        }

        val timeView = TextView(parent.context).apply {
            textSize = 12f
            setTextColor(android.graphics.Color.parseColor("#999999"))
            setPadding(0, 8, 0, 0)
        }

        itemView.addView(headerLayout)
        itemView.addView(orderNoView)
        itemView.addView(amountView)
        itemView.addView(timeView)

        return ViewHolder(itemView, merchantNameView, statusView, orderNoView, amountView, timeView)
    }

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        val order = orders[position]
        
        holder.merchantNameView.text = order.merchantName
        holder.statusView.text = getStatusText(order.status)
        holder.orderNoView.text = "订单号: ${order.orderNo}"
        holder.amountView.text = "¥${order.finalAmount}"
        holder.timeView.text = order.createdAt
        
        holder.itemView.setOnClickListener { onItemClick(order) }
    }

    override fun getItemCount() = orders.size

    private fun getStatusText(status: Int): String {
        return when (status) {
            OrderStatus.PENDING.value -> "待接单"
            OrderStatus.ACCEPTED.value -> "已接单"
            OrderStatus.PICKED_UP.value -> "已取件"
            OrderStatus.PROCESSING.value -> "处理中"
            OrderStatus.COMPLETED.value -> "已完成"
            OrderStatus.DELIVERED.value -> "已送达"
            OrderStatus.CANCELLED.value -> "已取消"
            OrderStatus.REFUNDED.value -> "已退款"
            else -> "未知状态"
        }
    }

    private fun createItemBackground(): android.graphics.drawable.Drawable {
        val drawable = android.graphics.drawable.GradientDrawable()
        drawable.setColor(android.graphics.Color.WHITE)
        drawable.setStroke(1, android.graphics.Color.parseColor("#E0E0E0"))
        drawable.cornerRadius = 8f
        return drawable
    }

    class ViewHolder(
        val itemView: View,
        val merchantNameView: TextView,
        val statusView: TextView,
        val orderNoView: TextView,
        val amountView: TextView,
        val timeView: TextView
    ) : RecyclerView.ViewHolder(itemView)
}

// 订单仓库类（简化版）
class OrderRepository(private val context: android.content.Context) {
    suspend fun getOrders(status: Int? = null): Result<com.laundry.user.data.api.PagedResponse<Order>> {
        // 这里应该调用实际的API
        // 暂时返回模拟数据
        return try {
            val mockOrders = listOf<Order>()
            val pagedResponse = com.laundry.user.data.api.PagedResponse(
                items = mockOrders,
                total = mockOrders.size,
                page = 1,
                size = 20,
                pages = 1,
                hasNext = false,
                hasPrev = false
            )
            Result.success(pagedResponse)
        } catch (e: Exception) {
            Result.failure(e)
        }
    }
}
